/**
 *
 *  首场景 
 *
 */
class MainScreen extends BaseScreen {
    public word1: eui.Image;
    public word2: eui.Image;
    public npc: eui.Image;
    public personBuild: eui.Group;
    public startBtn: eui.Image;
    private map: eui.Group;
    public loading: eui.Group;
    private moveOver: boolean = false;       //人物移动是否结束    
    private sourceLoadOver: boolean = false;   //下个场景资源是否加载完
    private curScene: number;

    private canDrag: boolean = true;
    private touchObj = {
        targetY: 0,
        lastY: 0,
        curPointID: -1,
        isTouching: false,
        moveOver: true
    };
    //底部坐标
    private bottomY: number = 3415;
    private screenRect: egret.Rectangle;
    private startBtnDownPos: egret.Point;
    // 人物保持相对屏幕的位置
    private boundary:number;
    //地图第一次下拉的位置
    private jumpY:number=-450;
    public processText: eui.Label;

    //人物运动轨迹
    public trackArr = [
        { 'x': 167, 'y': 956 },
        { 'x': 119, 'y': 1237 },
        { 'x': 286, 'y': 1394 },
        { 'x': 550, 'y': 1505 },
        { 'x': 536, 'y': 1631 },
        { 'x': 294, 'y': 1742 },
        { 'x': 88, 'y': 1878 },
        { 'x': 70, 'y': 2032 },
        { 'x': 460, 'y': 2225 },
        { 'x': 538, 'y': 2347 },
        { 'x': 205, 'y': 2561 },
        { 'x': 139, 'y': 2734 },
        { 'x': 221, 'y': 2879 },
        { 'x': 431, 'y': 2970 },
        { 'x': 372, 'y': 3147 }
    ];
    //移动的节点数组
    private sectionConfig = [{ pointNum: 0, moveTime: .6 },
    { pointNum: 1, moveTime: 1.2 },
    { pointNum: 5, moveTime: 1.4 },
    { pointNum: 9, moveTime: .9 },
    { pointNum: 11, moveTime: .9 },
    { pointNum: 14, moveTime: 0 }];

    public constructor() {
        super();
        this.skinName = "resource/eui_skins/MainScreenSkin.exml";
    }

    protected childrenCreated(): void {
        super.childrenCreated();
        this.initView();
    }

    private initView(): void {
        this.curScene = 0;
        this.boundary=this.trackArr[0].y+this.jumpY;
        this.startBtnDownPos = new egret.Point();
        this.word1.alpha = 0;
        this.word2.alpha = 0;
        this.npc.alpha = 0;
        this.npc.scaleX = .96;
        this.npc.scaleY = .96;
        this.screenRect = new egret.Rectangle(0, 0, this.width, this.height);
        this.showEffect();
    }
    // 重新开始重置
    private resetView():void
    {
        this.touchObj.curPointID = -1;
        this.touchObj.isTouching = false;
        this.touchObj.moveOver = true;
        this.touchObj.targetY=0;
        this.curScene=0;
        this.canDrag=true;
        this.map.y=this.jumpY;
        this.npc.x=this.trackArr[0].x;
        this.npc.y=this.trackArr[0].y;
        this.updataDepth();
        this.updataObjectsShow();

        this.startBtn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.startBtnDown, this);
        this.startBtn.addEventListener(egret.TouchEvent.TOUCH_END, this.startBtnUp, this);
        this.addEventListener(egret.Event.ENTER_FRAME, this.enterHandle, this);
    }

    private showEffect(): void {
        this.backOut(this.word1, .7, 0, 15, 0.3);
        this.backOut(this.word2, .7, -0, 24, .45);
        TweenMax.to(this.npc, .35, { scaleX: 1, scaleY: 1, alpha: 1, ease: Linear.easeOut, delay: .8 });
        TweenMax.to(this.map, .9, { y: this.jumpY, delay: 1.4, ease: Cubic.easeOut, onUpdate: this.updataObjectsShow.bind(this), onComplete: this.pushScreenOver.bind(this) });
    }
    // 将屏幕下拉
    private pushScreenOver(): void {
        this.map.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.mapTouchHandle, this);
        this.map.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.mapTouchHandle, this);
        this.map.addEventListener(egret.TouchEvent.TOUCH_END, this.mapTouchHandle, this);
        this.map.addEventListener(egret.TouchEvent.TOUCH_CANCEL, this.mapTouchHandle, this);

        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onLoadResourceLoadComplete, this);
		RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);

        this.startBtn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.startBtnDown, this);
        this.startBtn.addEventListener(egret.TouchEvent.TOUCH_END, this.startBtnUp, this);
        this.addEventListener(egret.Event.ENTER_FRAME, this.enterHandle, this);
        pub.SignalManager.instance.addSignal(pub.SignalDefin.NEXT_STEP,this.moveActorOneStep,this);
        pub.SignalManager.instance.addSignal(pub.SignalDefin.RESET_GAME,this.resetView,this);
    }
    //地图触摸事件
    private mapTouchHandle(e: egret.TouchEvent): void {
        if (!this.canDrag) return;
        switch (e.type) {
            case "touchBegin":
                if (this.touchObj.curPointID != -1) return;
                this.touchObj.curPointID = e.touchPointID;
                this.touchObj.targetY = this.map.y;
                this.touchObj.lastY = e.stageY;
                this.touchObj.isTouching = true;
                this.touchObj.moveOver = false;
                break
            case "touchMove":
                if (this.touchObj.curPointID != e.touchPointID) return;
                let disY: number = e.stageY - this.touchObj.lastY;
                this.getMapTargetY(disY);
                this.touchObj.lastY = e.stageY;
                break
            case "touchEnd":
                if (this.touchObj.curPointID != e.touchPointID) return;
                this.touchObj.curPointID = -1;
                this.touchObj.isTouching = false;
                break
            case "touchCancel":
                this.touchObj.isTouching = false;
                break
        }
    }
    //获取地图移动的目标位置
    private getMapTargetY(disY: number): void {
        let tempTargetY: number = this.touchObj.targetY + disY;
        if (tempTargetY > 0) tempTargetY = 0;
        if (tempTargetY < this.height - this.bottomY) {
            tempTargetY = this.height - this.bottomY;
        }
        this.touchObj.targetY = tempTargetY;
    }
    //缓动的更新地图的位置
    private easeUpdataMapPos(): void {
        this.map.y += (this.touchObj.targetY - this.map.y) * 0.5;
        if (!this.touchObj.isTouching) {
            if (Math.abs(this.map.y - this.touchObj.targetY) < 0.1) {
                this.map.y = this.touchObj.targetY;
                this.touchObj.moveOver = true;
            }
        }
        this.updataObjectsShow();
    }
    private enterHandle(e: egret.Event): void {
        if (this.touchObj.isTouching || !this.touchObj.moveOver) {
            this.easeUpdataMapPos();
        }
    }

    private startBtnDown(e: egret.TouchEvent): void {
        console.log('startBtnDown.......');
        this.startBtnDownPos.x=e.stageX;
        this.startBtnDownPos.y=e.stageY;
    }

    private startBtnUp(e: egret.TouchEvent): void {
        console.log('startBtnUp.......');
        if (e.stageX != this.startBtnDownPos.x || e.stageY != this.startBtnDownPos.y) return;
        this.startBtn.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.startBtnDown, this);
        this.startBtn.removeEventListener(egret.TouchEvent.TOUCH_END, this.startBtnUp, this);
        this.removeEventListener(egret.Event.ENTER_FRAME, this.enterHandle, this);
        // this.canDrag = false;
        // this.moveActorOneStep();
        // this.loadGradeSource();
        utils.ScreenManager.instance.changeScreen("Scene6",false);
    }

    //移动主角
    private moveActorOneStep(): void {
        let curConfig = this.sectionConfig[this.curScene];
        let nextConfig = this.sectionConfig[this.curScene + 1];
        let posArr = this.trackArr.slice(curConfig.pointNum+1,nextConfig.pointNum+1);
        TweenMax.to(this.npc, curConfig.moveTime, { bezier: posArr, ease: Quad.easeInOut, onUpdate: this.moveNpcUpdata.bind(this), onComplete: this.moveComplete.bind(this) });
    }
    //当移动npc的时候更新视图
    private moveNpcUpdata(): void {
        this.updataDepth();
        this.adjustMapPos();
        this.updataObjectsShow();
    }
    //调整地图的位置
    private adjustMapPos(): void {
        let relativeY:number=this.npc.y+this.map.y;
        if(relativeY<=this.boundary) return;
        let offsetY=relativeY-this.boundary;
        let tempMapY:number=this.map.y-offsetY;
        if(tempMapY<this.height - this.bottomY){
            tempMapY=this.height - this.bottomY;
        }
        this.map.y=tempMapY;
    }
    //更新建筑和人的图层顺序
    private updataDepth():void
    {
        for(let i:number=1;i<=7;i++){
            let curBuild:eui.Image=<eui.Image>(this['build'+i]);
            if(this.npc.y<curBuild.y){
                this.personBuild.addChildAt(this.npc,i-1);
                break;
            }
        }
    }

    //加载下一页的资源
    private loadGradeSource(): void {
        RES.loadGroup(`scene${this.curScene + 2}`);
    }
    //加载group结束
    private onLoadResourceLoadComplete(event: RES.ResourceEvent): void {
        this.sourceLoadOver = true;
        if (this.moveOver) this.changeScreen();
    }
    //主角移动完成时间
    private moveComplete(): void {
        this.moveOver = true;
        if (this.sourceLoadOver) this.changeScreen();
        else this.loading.visible = true;
    }

    //移动地图 显示屏幕上的元素
    private updataObjectsShow(): void {
        this.screenRect.top = -this.map.y;
        this.screenRect.bottom = this.screenRect.top + this.height;
        this.showHideElements(this.map);
    }
    //更新子元素的显示
    private showHideElements(group: eui.Group): void {
        let childLen: number = group.numChildren;
        for (let i: number = 0; i < childLen; i++) {
            let child: egret.DisplayObject = <egret.DisplayObject>(group.getChildAt(i));
            if (child instanceof eui.Group) {
                this.showHideElements(child);
            } else {
                this.shiftShow(child);
            }
        }
    }
    //测试子元素是否当前正在显示
    private shiftShow(element: egret.DisplayObject): void {
        if (!element['rect_top']) {
            element['rect_top'] = element.y - element.anchorOffsetY;
            element['rect_bottom'] = element['rect_top'] + element.height;
        }else if(element==this.npc){
            element['rect_top'] = element.y - element.anchorOffsetY;
            element['rect_bottom'] = element['rect_top'] + element.height;
        }

        if (element['rect_bottom'] < this.screenRect.top || element['rect_top'] > this.screenRect.bottom) {
            if (element.visible) element.visible = false;
        } else {
            if (!element.visible) element.visible = true;
        }
    }
    //转换场景
    private changeScreen(): void {
        this.loading.visible = false;
        utils.ScreenManager.instance.changeScreen(`Scene${this.curScene + 2}`,false);
        this.curScene++;
    }

    /**
     * preload资源组加载进度
     * loading process of preload resource
     */
	private onResourceProgress(event: RES.ResourceEvent): void {
		if (!this.loading.visible) return;
		this.processText.text = Math.floor(event.itemsLoaded * 100 / event.itemsTotal) + "%";
	}

    public resize(): void {
        super.resize();
    }

    public dispose(): void {
        TweenMax.killAll(false, false, true);
        TweenMax.killChildTweensOf(this);
    }

}
